const {ccclass, property} = cc._decorator
import BattleCardBo from "../model/BattleCardBo"
import {loadRes, roll} from "../utils/HonganUtil"
import { EVENT_TYPE } from "../common/enums"
import BattleCard from "./BattleCard"
import AttackCtx from "../model/AttackCtx"
import AttackResult from "../model/AttackResult"



@ccclass
export default class BattleRoom extends cc.Component {

    @property({
        default:null,
        type:cc.Prefab
    })
    cardPrefab:cc.Prefab;

    private _card1:BattleCard;
    private _card2:BattleCard;
    private _battle_desc:cc.Label;

    async initCard<T extends cc.Component>(name:string, pic:string, x:number, y:number,bo:BattleCardBo):Promise<T >{
        var card = new cc.Node(name);
        var cardTitle = new cc.Node("cardTitle");
        var sp = card.addComponent(cc.Sprite);
        var bc = card.addComponent("BattleCard");
        var cardLabel = cardTitle.addComponent(cc.Label);
        card.addChild(cardTitle);
        card.setPositionX(x);
        card.setPositionY(y);
        var cardFrame = await loadRes<cc.SpriteFrame>(pic,cc.SpriteFrame) ;
        sp.spriteFrame = cardFrame; 
        bc.init(bo, cardLabel);
        this.node.addChild(card);
        return bc;
    }
    loadViews(){
        this._battle_desc = this.node.getChildByName("battleDesc").getComponent(cc.Label);
    }

    async initCards(){
        this._card1 = await this.initCard<BattleCard>("Card1","c01",10,-200,new BattleCardBo("玛丽露", 100, 20));
        this._card2 = await this.initCard<BattleCard>("Card2","c02",10,200,new BattleCardBo("大黄蜂",80,30));
    }

    showBattleStatus(attckCtx:AttackCtx){
        var desc = attckCtx.descibe();
        console.log(desc);
        this._battle_desc.string = desc;
    }


    //初始化controller 
    initController(){
        this.node.on(EVENT_TYPE.ATTACK,event => {
            event.stopPropagation();
            var attackResult = new AttackResult(false,0);
            if(!roll(50,100)){
                //打中
                attackResult.dmg = this._card1.getDmg();
                attackResult.hited = true;
                this._card2.takeDmg(attackResult.dmg);
            }
            this.showBattleStatus(new AttackCtx(this._card1.status, this._card2.status, attackResult));
        })
    }
    onLoad() {
        this.loadViews();
        this.initCards();
        this.initController();
    }
}
